<template>
  <div class="app-container">
    <!-- 搜索 -->
    <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
      @reset-click="handleResetClick">
      <!-- <template #reward_type="scope">
        <el-select v-model="searchParam[scope.prop]" @change="setSearchParam()" v-bind="scope">
          <template v-for="option in typeList" :key="option.value">
            <el-option :label="option.label" :value="option.value" />
          </template>
      </el-select> -->
    </page-search>
    <!-- 表格 -->
    <PageContent ref="contentRef" :gridOptions="gridOptions" :content-config="contentConfig" @addClick="handleAddClick"
      @edit-click="handleEditClick" @export-click="handleExportClick"
     >
      <template #status="scope">
        <!-- warning -->
        <el-tag :type="types[scope.row.status]">
          {{ t(`groupStatus.${scope.row.status}`)}}
        </el-tag>
      </template>
      <template #meta0="scope">
        <div v-if="scope.row.meta && scope.row.meta.length">
          <div v-for="(item, index) in scope.row.meta" :key="index">
            <template v-if="item.key === 'required_vip_level'">
              <span v-if="item.value">VIP{{ item.value }}</span>
            </template>
          </div>
        </div>
      </template>
      <template #meta1="scope">
        <div v-if="scope.row.meta && scope.row.meta.length">
          <div v-for="(item, index) in scope.row.meta" :key="index">
            <template v-if="item.key === 'can_send_messages'">
              <el-tag v-if="item.key === 'can_send_messages'" :type="item.value === '1' ? 'success' : 'danger'">
                {{ item.value === '1' ? t('label.163') : t('label.164') }}
              </el-tag>
            </template>
          </div>
        </div>
      </template>
    </PageContent>

    <!-- 修改/新增 -->
    <el-dialog v-model="dialogVisible" width="900" :title="isEdit ?  t('title.33'):t('title.32')" :close-on-click-modal="false" @close="closeDialog" align-center>
      <!-- 表单 -->
      <el-form ref="formRef" class="max-h-80vh overflow-auto w-full px-5" :model="formData" :rules="formRules" label-width="auto" label-position="top">
        <el-form-item :label="t('label.108')" prop="name">
          <el-input v-model="formData.name" :placeholder="t('hint.117')" />
        </el-form-item>
        <el-form-item :label="t('label.23')" prop="status">
          <el-select v-model="formData.status" :placeholder="t('hint.150')" >
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="meta" prop="meta">
          <div class="w-full">
            <el-row :gutter="15" class="w-full mb-2">
              <el-col :span="10">
                <el-input v-model="formData.meta[0].key" disabled  />
              </el-col>
              <el-col :span="10">
                <el-select v-model="formData.meta[0].value">
                  <el-option v-for="option in vipLevelList" :key="option.value" :label="option.label" :value="option.value" />
                </el-select>
              </el-col>
            </el-row>
            <el-row :gutter="15" class="w-full mb-2">
              <el-col :span="10">
                <el-input v-model="formData.meta[1].key" disabled  />
              </el-col>
              <el-col :span="10">
                <el-select v-model="formData.meta[1].value">
                  <el-option v-for="option in can_send_messages_position" :key="option.value" :label="option.label" :value="option.value" />
                </el-select>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{$t('btn.1')}}
          </el-button>
          <el-button @click="closeDialog">
            {{$t('btn.8')}}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import contentConfig from "./config/content";
import searchConfig from "./config/search";
import usePage from "@/hooks/usePage";
import { tableHeightAutoAdjust } from '@/utils/common'
import API from '@/api/client/levels.js'
import groupApi from '@/api/server/group'
defineOptions({
  name: "serverGroup",
  inheritAttrs: false,
});
const types = {
  "active": "success",
  "inactive": "danger",
}
const { t } = useI18n();

const gridOptions = reactive({})

const { searchRef, contentRef,
  handleExportClick, } = usePage();

function handleQueryClick(queryParams) {
  contentRef.value?.fetchPageData({...queryParams, type: "group"}, true)
}

const handleResetClick = () => {
  contentRef.value?.fetchPageData({
    type: "group"
  }, true)
}

// 初始化数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const loading = ref(false)

const formData = ref({
  id:"",
  name:"",
  type:"group",
  status:"",
  meta: [
    {
      key: 'required_vip_level',
      value: ''
    },
    {
      key: 'can_send_messages',
      value: ''
    }
  ],
})

// 打开编辑窗口
const handleEditClick = (row) => {
  console.log('row====>',row)
  dialogVisible.value = true
  isEdit.value = true
  // 赋值给formData,根据formData[i],应该根据formData键名从row[i]去赋值给formData[i]
  Object.keys(formData.value).forEach(key => {
    if (key === 'meta') {
      // 检查row[key]是否存在且是数组
      if (row[key] && Array.isArray(row[key]) && row[key].length > 0) {
        // 创建一个默认的meta结构
        const metaTemplate = [
          {
            key: 'required_vip_level',
            value: ''
          },
          {
            key: 'can_send_messages',
            value: ''
          }
        ];
        
        // 从row中找到对应的meta项并填充到正确的位置
        row[key].forEach(item => {
          if (item.key === 'required_vip_level') {
            metaTemplate[0].value = item.value;
          } else if (item.key === 'can_send_messages') {
            metaTemplate[1].value = item.value;
          }
        });
        
        formData.value[key] = metaTemplate;
      } else {
        // 如果meta为空或不存在，使用默认值
        formData.value[key] = [
          {
            key: 'required_vip_level',
            value: ''
          },
          {
            key: 'can_send_messages',
            value: ''
          }
        ]
      }
    } else {
      formData.value[key] = row[key]
    }
  })

  console.log('formData===>',formData.value)
}

const vipLevelList = ref([])
const can_send_messages_position = ref([
  { label: t('label.163'), value: "1" },
  { label: t('label.164'), value: "0" },
])

const statusOptions = ref([
{ label: t("groupStatus.active"), value: 'active' },
{ label: t("groupStatus.inactive"), value: 'inactive' },
])

// 打开新建窗口
const handleAddClick = () => {
  dialogVisible.value = true
  isEdit.value = false
}


const closeDialog = () => {
  formData.value = {
    id: "",
    name: "",
    type: "group",
    status: "",
    meta: [
      {
        key: 'required_vip_level',
        value: ''
      },
      {
        key: 'can_send_messages',
        value: ''
      }
    ],
  }
  formRef.value.clearValidate()
  dialogVisible.value = false
}

const formRef = ref(null)
// 规则校验
const formRules = ref({
  status: [{ required: true, message: t("hint.150"), trigger: "change" }],
  name: [{ required: true, message: t("hint.117"), trigger: "blur" }],
  meta: [{
    validator: (rule, value, callback) => {
      // 检查value是否为空
      if (!value || !value.length) {
        callback(new Error(t('hint.129')));
        return;
      }
      
      // 检查第一个item的key和value
      if (!value[0].key || value[0].value === undefined || value[0].value === '') {
        callback(new Error(t('hint.129')));
        return;
      }
      
      // 检查所有item的key和value
      for (let i = 0; i < value.length; i++) {
        if (!value[i].key || value[i].value === undefined || value[i].value === '') {
          callback(new Error(t('hint.131', {value: i + 1})));
          return;
        }
      }
      
      callback();
    },
    trigger: ['blur', 'change']
  }],
})

/**
 * 提交方法
 */
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      
      if (formData.value.id) {
        groupApi.put(formData.value).then((s) => {
          ElMessage.success(t("hint.107"))
          handleQueryClick()
          closeDialog()
        }).finally(() => {
          loading.value = false
          dialogVisible.value = false
        })
      } else {
        groupApi.add(formData.value).then((s) => {
          ElMessage.success(t("hint.108"))
          handleQueryClick()
          closeDialog()
        }).finally(() => {
          loading.value = false
          dialogVisible.value = false
        })
      }
    }
  })
}

function getVipLevelList() {
  API.getList().then((res) => {
    vipLevelList.value = res.data.map((item) => {
      return {
        label: item.name,
        value: String(item.level),
      }
    })
  });
}

onMounted(() => {
  handleQueryClick(searchRef.value.getQueryParams())
  // 确保在组件挂载后立即设置高度
  tableHeightAutoAdjust(gridOptions);
  // 获取会员等级
  getVipLevelList();
})
</script>

<style></style>